<template>
  <div class="main">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <div class="card-title">物料清单</div>
          <div class="card-tools">
            <el-button type="primary" @click="handleAdd">新增物料</el-button>
            <el-button 
              v-if="multipleSelection.length > 0" 
              type="danger" 
              @click="handleBatchDelete"
              class="ml-2"
            >
              批量删除
            </el-button>
          </div>
        </div>
      </template>
      
      <!-- 搜索区域 -->
      <div class="search-area mb-4">
        <el-input
          v-model="searchForm.keyword"
          placeholder="请输入物料名称/品牌"
          prefix-icon="Search"
          @keydown.enter="handleSearch"
        >
          <template #append>
            <el-button @click="handleSearch" class="search-button">搜索</el-button>
            <el-button @click="handleReset" class="reset-button">清空</el-button>
          </template>
        </el-input>
      </div>

      <!-- 表格区域 -->
      <el-table
        ref="multipleTableRef"
        v-loading="loading"
        :data="materialList"
        style="width: 100%"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="id" label="序号" width="80" type="index" align="center">
          <template #default="scope">
            {{ (pagination.page - 1) * pagination.limit + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="name" label="物料名称" min-width="180" align="center" />
        <el-table-column prop="brand" label="品牌" min-width="150" align="center" />
        <el-table-column prop="specification" label="规格型号" min-width="150" align="center" />
        <el-table-column prop="unit" label="单位" min-width="100" align="center" />
        <el-table-column prop="remark" label="备注" min-width="200" align="center" show-overflow-tooltip />
        <el-table-column label="操作" width="150" align="center" fixed="right">
          <template #default="scope">
            <el-button type="text" @click="handleEdit(scope.row)" size="small">修改</el-button>
            <el-button type="text" @click="handleDelete(scope.row)" size="small" danger>删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination mt-4 flex justify-end items-center">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.limit"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑物料' : '新增物料'"
      width="500px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="物料名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入物料名称" />
        </el-form-item>
        <el-form-item label="品牌" prop="brand">
          <el-input v-model="formData.brand" placeholder="请输入品牌" />
        </el-form-item>
        <el-form-item label="规格型号" prop="specification">
          <el-input v-model="formData.specification" placeholder="请输入规格型号" />
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="formData.unit" placeholder="请输入单位" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input 
            v-model="formData.remark" 
            type="textarea" 
            placeholder="请输入备注信息" 
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleDialogClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>


  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import type { MaterialItem, MaterialListParams, MaterialPayload } from '@/api/material';
import { getMaterialList, createMaterial, updateMaterial, deleteMaterial, getMaterialById, deleteBatchMaterial } from '@/api/material';

// 分页相关数据
const pagination = reactive({
  page: 1,
  limit: 10,
  total: 0
});

// 搜索表单数据
const searchForm = reactive({
  keyword: ''
});

// 物料列表数据
const materialList = ref<MaterialItem[]>([]);

// 表格加载状态
const loading = ref(false);

// 对话框相关数据
const dialogVisible = ref(false);
const isEdit = ref(false);
const formRef = ref<FormInstance>();
const formData = reactive<Partial<MaterialPayload & { id: number }>>({});
let currentMaterialId = 0;

// 多选相关数据
const multipleTableRef = ref();
const multipleSelection = ref<MaterialItem[]>([]);

// 表单验证规则
const formRules = reactive<FormRules>({
  name: [{ required: true, message: '请输入物料名称', trigger: 'blur' }],
  brand: [{ required: true, message: '请输入品牌', trigger: 'blur' }],
  specification: [{ required: true, message: '请输入规格型号', trigger: 'blur' }],
  unit: [{ required: true, message: '请输入单位', trigger: 'blur' }]
});



// 获取物料列表
const fetchMaterialList = async () => {
  try {
    loading.value = true;
    // 构建查询参数
    const params: MaterialListParams = {
      page: pagination.page,
      limit: pagination.limit,
      ...(searchForm.keyword && { name: searchForm.keyword })
    };
    
    // 调用API获取物料列表
    const res = await getMaterialList(params);
    
    // 检查数据结构并适配
    if (res.code === 0) {
      // 检查数据结构并适配
      if (res.data && res.data.list && Array.isArray(res.data.list)) {
        // 直接使用list数组
        materialList.value = res.data.list;
        pagination.total = res.data.total || 0;
      } else {
        // 处理特殊情况：如果返回的数据结构与预期不同
        // 尝试从其他可能的字段中提取数据
        if (res.data && typeof res.data === 'object') {
          // 适配接口文档中的特殊情况
          if (res.data.records && Array.isArray(res.data.records)) {
            // 使用records字段
            materialList.value = res.data.records;
            pagination.total = res.data.total || 0;
          } else if (res.data.b && typeof res.data.b === 'object') {
            // 适配网络请求截图中显示的特殊格式
            if (res.data.b.records && Array.isArray(res.data.b.records)) {
              materialList.value = res.data.b.records;
              pagination.total = res.data.b.total || 0;
            }
          }
        }
        
        if (materialList.value.length === 0 && process.env.NODE_ENV === 'development') {
          console.warn('获取物料列表成功但数据为空');
        }
      }
    } else {
      ElMessage.error(res.message || '获取物料列表失败');
      materialList.value = [];
      pagination.total = 0;
    }
  } catch (error) {
    console.error('获取物料列表失败:', error);
    ElMessage.error('获取物料列表失败');
    materialList.value = [];
    pagination.total = 0;
  } finally {
    loading.value = false;
  }
};

// 搜索功能
const handleSearch = () => {
  pagination.page = 1;
  fetchMaterialList();
};

// 重置搜索
const handleReset = () => {
  searchForm.keyword = '';
  pagination.page = 1;
  fetchMaterialList();
};

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.limit = size;
  pagination.page = 1;
  fetchMaterialList();
};

// 当前页码改变
const handleCurrentChange = (current: number) => {
  pagination.page = current;
  fetchMaterialList();
};

// 打开新增物料对话框
const handleAdd = () => {
  isEdit.value = false;
  // 重置表单数据
  Object.assign(formData, {
    name: '',
    brand: '',
    specification: '',
    unit: '',
    remark: ''
  });
  dialogVisible.value = true;
};

// 打开编辑物料对话框
const handleEdit = async (row: MaterialItem) => {
  isEdit.value = true;
  currentMaterialId = row.id;
  
  try {
    const res = await getMaterialById(row.id);
    if (res.code === 0 && res.data) {
      Object.assign(formData, res.data);
      dialogVisible.value = true;
    } else {
      ElMessage.error(res.message || '获取物料详情失败');
    }
  } catch (error) {
    console.error('获取物料详情失败:', error);
    ElMessage.error('获取物料详情失败');
  }
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;
  
  try {
    await formRef.value.validate();
    
    if (isEdit.value) {
      // 修改物料
      const res = await updateMaterial({ ...formData, id: currentMaterialId } as MaterialPayload & { id: number });
      if (res.code === 0) {
        ElMessage.success('修改成功');
        dialogVisible.value = false;
        fetchMaterialList();
      } else {
        ElMessage.error(res.message || '修改失败');
      }
    } else {
      // 新增物料
      const res = await createMaterial(formData as MaterialPayload);
      if (res.code === 0) {
        ElMessage.success('新增成功');
        dialogVisible.value = false;
        fetchMaterialList();
      } else {
        ElMessage.error(res.message || '新增失败');
      }
    }
  } catch (error) {
    console.error('表单验证失败:', error);
  }
};

// 关闭对话框
const handleDialogClose = () => {
  dialogVisible.value = false;
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

// 删除物料
const handleDelete = (row: MaterialItem) => {
  ElMessageBox.confirm('确定要删除这个物料吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await deleteMaterial(row.id);
      if (res.code === 0) {
        ElMessage.success('删除成功');
        fetchMaterialList(); // 重新获取物料列表
      } else {
        ElMessage.error(res.message || '删除失败');
      }
    } catch (error) {
      console.error('删除物料失败:', error);
      ElMessage.error('删除失败');
    }
  }).catch(() => {
    // 用户取消删除
  });
};



// 多选处理函数
const handleSelectionChange = (val: MaterialItem[]) => {
  multipleSelection.value = val;
};

// 切换选中状态
const toggleSelection = (rows?: MaterialItem[]) => {
  if (!multipleTableRef.value) return;
  
  if (rows) {
    rows.forEach(row => {
      (multipleTableRef.value as any).toggleRowSelection(row);
    });
  } else {
    (multipleTableRef.value as any).clearSelection();
  }
};

// 批量删除
const handleBatchDelete = () => {
  ElMessageBox.confirm('确定要删除选中的物料吗？', '确认删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const ids = multipleSelection.value.map(item => item.id);
      const res = await deleteBatchMaterial({ ids });
      if (res.code === 0) {
        ElMessage.success('批量删除成功');
        fetchMaterialList();
      } else {
        ElMessage.error(res.message || '批量删除失败');
      }
    } catch (error) {
      console.error('批量删除失败:', error);
      ElMessage.error('批量删除失败');
    }
  }).catch(() => {
    // 用户取消删除
  });
};

// 初始加载数据
onMounted(() => {
  fetchMaterialList();
});
</script>

<style scoped>
.main {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 18px;
  font-weight: 600;
}

.search-area {
  margin-bottom: 16px;
}

.search-button {
  margin-right: 8px;
}

.reset-button {
  color: #606266;
}

.pagination {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
</style>